package com.pricetag.serversdk;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;

import com.google.gson.Gson;

// java Client fileNameOfImage
public class ServerProxy {
	private Gson gson = new Gson();
	private final String serverDomain = "http://54.241.13.111:8080";

	public static void main(String[] args) throws IOException, URISyntaxException {
		ServerProxy c = new ServerProxy();

		// upload file
		/*
		 * URL defaultImage =
		 * CommunicationClient.class.getResource("/images/2.jpg"); File
		 * fileToUpload = new File(defaultImage.toURI()); String name =
		 * c.uploadImage(fileToUpload);
		 */

		// example for search with image google
		// GoogleImageNameSearchResult gr =
		// c.getImageNameFromGoogle("20130319062007564_2.jpg");

		// example for local database
		// LocalStorePriceSearchResult ls =
		// c.searchLocalImage("20130316010851668_1.jpg");
	}

	public String uploadImage(File imageFile) throws URISyntaxException {
		final String EOL = "\r\n";
		final String MULTIPART_BOUNDARY = "------------------563i2ndDfv2rTHiSsdfsdbouNdArYfORhxcvxcvefj3q2f";
		final String UPLOADED_FILE_NAME = imageFile.getName();
		String url = serverDomain + "/upload";
		File fileToUpload = imageFile;

		HttpURLConnection connection = null;
		OutputStream os = null;
		DataInputStream is = null;
		try {
			connection = (HttpURLConnection) new URL(url).openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + MULTIPART_BOUNDARY);
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.connect();
			os = new BufferedOutputStream(connection.getOutputStream());
			if (os != null) {
				os.write(("--" + MULTIPART_BOUNDARY + EOL).getBytes());
				os.write(String
						.format("Content-Disposition:form-data;name=\"data\";filename=\"%s\"\r\nContent-Type: application/x-zip-compressed\r\n\r\n",
								UPLOADED_FILE_NAME).getBytes());
				is = new DataInputStream(new FileInputStream(fileToUpload));
				int a = 0;
				try {
					while (is.available() > 0) {
						byte[] byteArray = new byte[1024];
						a += is.read(byteArray);
						os.write(byteArray);
					}
				} finally {
					if (is != null)
						try {
							is.close();
						} catch (IOException logOrIgnore) {
						}
				}
				System.err.println(a + " Bytes uploaded.");

				os.write((EOL + "--" + MULTIPART_BOUNDARY + "--" + EOL + EOL).getBytes());
				os.flush();
				os.close();
				os = null;
			}
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				String line = null;
				while ((line = in.readLine()) != null) {
					ImageUploadResult result = gson.fromJson(line, ImageUploadResult.class);
					System.out.println(result.getImage_file());
					return result.getImage_file();
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();

		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
			}
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
			}
			if (connection != null) {
				connection.disconnect();
			}

		}

		return null;
	}

	public LocalImageDBSearchResult searchLocalImage(String remoteName){
		return searchLocalImage(remoteName,"camera");
	}
	
	public LocalImageDBSearchResult searchLocalImage(String remoteName, String category ) {
		category = URLEncoder.encode(category);
		String url = serverDomain + "/search?image_file=" + remoteName + "&mode=2&location=local"+ "&category="+category;
		System.err.println(url);
		HttpURLConnection connection = null;
		OutputStream os = null;
		try {
			connection = (HttpURLConnection) new URL(url).openConnection();
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.connect();
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				String line = null;
				while ((line = in.readLine()) != null) {
					LocalImageDBSearchResult result = gson.fromJson(line, LocalImageDBSearchResult.class);
					System.out.println("local image name is " + result.getName());
					if (result == null || result.getName() == null || result.getName().equals("null")
							|| result.getName().equals("")) {
						return null;
					} else {
						return result;
					}
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();

		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
			}
			if (connection != null) {
				connection.disconnect();
			}

		}

		return null;
	}

	public String getImageNameFromGoogle(String remoteName) {
		String url = serverDomain + "/search?image_file=" + remoteName + "&mode=1&location=local";
		HttpURLConnection connection = null;
		OutputStream os = null;
		try {
			connection = (HttpURLConnection) new URL(url).openConnection();
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.connect();
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				String line = null;
				while ((line = in.readLine()) != null) {
					GoogleImageNameSearchResult result = gson.fromJson(line, GoogleImageNameSearchResult.class);
					if (result.getGuessName() != null && result.getGuessName().equals("unknown")) {
						return null;
					}
					System.out.println("Google Goggle image name is " + result.getGuessName());
					return result.getGuessName();
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();

		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
			}
			if (connection != null) {
				connection.disconnect();
			}

		}

		return null;
	}

}
